// src/hooks/useDateTimeFormatter.js
import { useState, useEffect, useCallback } from "react";

const useDateTimeFormatter = (isoString, options = {}) => {
  const {
    showFullDate = false,
    refreshInterval = 1000,
    localTime = true,
  } = options;

  const parseTime = useCallback(() => {
    const date = new Date(isoString);
    return localTime ? date : new Date(date.toISOString());
  }, [isoString, localTime]);

  const calculateRelativeTime = useCallback(
    (date) => {
      const now = new Date();
      const diffSeconds = Math.round((now - date) / 1000);
      const diffMinutes = Math.round(diffSeconds / 60);
      const diffHours = Math.round(diffMinutes / 60);
      const diffDays = Math.round(diffHours / 24);

      if (diffSeconds < 60) return `${diffSeconds}秒前`;
      if (diffMinutes < 60) return `${diffMinutes}分钟前`;
      if (diffHours < 24) return `${diffHours}小时前`;
      if (diffDays === 1) return "昨天";
      if (diffDays < 7) return `${diffDays}天前`;

      return showFullDate
        ? date.toLocaleDateString("zh-CN", {
            year: "numeric",
            month: "long",
            day: "numeric",
            hour: "2-digit",
            minute: "2-digit",
          })
        : date.toLocaleDateString();
    },
    [showFullDate]
  );

  const [formattedTime, setFormattedTime] = useState(() => {
    const date = parseTime();
    return calculateRelativeTime(date);
  });

  useEffect(() => {
    const date = parseTime();
    const updateTime = () => {
      setFormattedTime(calculateRelativeTime(date));
    };

    let interval = refreshInterval;
    const diff = Date.now() - date;

    if (diff > 86400000) {
      interval = 3600000;
    } else if (diff > 3600000) {
      interval = 600000;
    }

    const timer = setInterval(updateTime, interval);
    return () => clearInterval(timer);
  }, [isoString, calculateRelativeTime, parseTime, refreshInterval]);

  return {
    formattedTime,
    originalDate: parseTime(),
    isoString: parseTime().toISOString(),
  };
};

export default useDateTimeFormatter;
